<template>
  <section>
    <el-form :model="formInline" :rules="rules" ref="ruleFormRef">
      <ul class="form-box">
        <li>
          <el-form-item label="服务中文名称" prop="svcName">
            <el-input
              v-model="formInline.svcName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </li>
        <li>
          <el-form-item label="方法名称" prop="svcUrl">
            <el-input
              v-model="formInline.svcUrl"
              placeholder="请输入方法名称(methodName)"
            ></el-input>
          </el-form-item>
        </li>
        <li>
          <el-form-item label="所属应用" prop="appId" class="form">
            <el-select
              v-model="formInline.appId"
              placeholder="请选择"
              filterable
              remote
              :remote-method="appRemote"
              @change="appRemote('')"
            >
              <el-option
                :label="item.appName + '-' + item.orgName"
                :value="item.id"
                v-for="(item, index) in appListInfo.list"
                :key="index"
              >
              </el-option>
              <el-pagination
                small
                background
                @current-change="getAppList"
                :page-size="10"
                layout="prev, pager, next"
                :total="appListInfo.total"
              >
              </el-pagination>
            </el-select>
          </el-form-item>
        </li>
        <li>
          <el-form-item label="服务调用超时" prop="callTimeout">
            <el-input
              v-model="formInline.callTimeout"
              placeholder="请输入时间"
              type="Number"
              ><template #append>ms</template>
            </el-input>
          </el-form-item>
        </li>
        <li>
          <el-form-item label="当前版本">
            <el-select
              v-model="formInline.currentVersionId"
              placeholder="请选择"
            >
              <el-option
                :label="item.versionNum"
                :value="item.versionId"
                v-for="(item, index) in versionList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </li>
        <li>
          <el-form-item label="服务标签">
            <el-select v-model="formInline.tags" placeholder="请选择" multiple>
              <el-option
                :label="item.label"
                :value="item.id"
                v-for="(item, index) in tagsList"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </li>
        <li>
          <el-form-item label="是否上传IRS" prop="irsAppId">
            <el-radio-group v-model="formInline.uploadIrs">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </li>
        <!-- 0223022新增 -->
        <li>
          <el-form-item label="共享类型" prop="shareType">
            <el-select v-model="formInline.shareType" placeholder="请选择">
              <el-option
                :label="item"
                :value="index"
                v-for="(item, index) in shareList"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </li>
        <li>
          <el-form-item label="领域分类" prop="domainType">
            <el-select v-model="formInline.domainType" placeholder="请选择">
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="(item, index) in domainList"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </li>
        <li>
          <el-form-item label="敏感等级" prop="sensitiveLevel">
            <el-select v-model="formInline.sensitiveLevel" placeholder="请选择">
              <el-option
                :label="item"
                :value="index"
                v-for="(item, index) in sensitiveList"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </li>

        <li class="affiliation-app">
          <el-form-item label="运维人员" class="from" prop="createdUserCode">
            <el-input v-model="formInline.createdUserName" disabled />
            <el-input
              v-model="formInline.createdUserCode"
              disabled
              v-show="false"
            />
            <el-button type="primary" class="new-btn" @click="selectZzdUser"
              >选择</el-button
            >
          </el-form-item>
        </li>
        <li>
          <el-form-item label="标准化返回" prop="wrapped">
            <el-radio-group v-model="formInline.wrapped">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </li>
        <li>
          <el-form-item label="描述" prop="memo">
            <el-input
              v-model="formInline.memo"
              placeholder="请输入描述"
              :autosize="{ minRows: 2, maxRows: 4 }"
              type="textarea"
            ></el-input>
          </el-form-item>
        </li>
        <p>
          <el-form-item style="display: block; float: right">
            <el-button type="primary" @click="saveServiceSubmit('save')" plain
              >保存</el-button
            >
          </el-form-item>
        </p>
      </ul>
    </el-form>
    <div class="divider-line"></div>
    <div class="verstion">
      <h4 class="divider">
        版号编辑
        <el-button type="primary" class="fr" @click="saveServiceSubmit('creat')"
          >创建新版本</el-button
        >
      </h4>
      <el-table :data="versionList" style="width: 100%" class="verstion-table">
        <el-table-column prop="versionNum" label="版本号" />
        <el-table-column prop="auditSts" label="状态">
          <template #default="scope">
            {{ auditCode[scope.row.auditSts] }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click.prevent="editRow(scope.row.versionId)"
              :disabled="scope.row.auditSts !== 'T'"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              @click.prevent="cancelVerstion(scope.row.versionId, scope.$index)"
              :disabled="scope.row.auditSts == 'D'"
            >
              作废
            </el-button>
            <el-button
              type="text"
              size="small"
              @click.prevent="getDetailShow(null, scope.row.versionId)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <Detail v-model="showDetail" :detailInfo="detailInfo" mode="version" />
    <SelectUser
      @query-change="queryChange"
      v-model="showZzdSelcet"
    ></SelectUser>
  </section>
</template>

<script setup>
import { getUserInfo } from "@/api/system";
import { ElMessageBox, ElMessage } from "element-plus";
import { reactive, ref, onMounted, watch, computed } from "vue";
import { useStore } from "vuex";
import { useRoute } from "vue-router";
import {
  saveService,
  abolishVersion,
  versionService,
  getTagsPageList,
  getIrsSystemApi,
  getIrsSystemDetail,
} from "@/api/service.js";
import { getAppPageList, getAppDetail } from "@/api/application.js";
import { auditCode, string2obj, string2Arr } from "@/utils/index.js";
import { getNodePageList, getAuthPageList } from "@/api/adaptation.js";
import Detail from "./detail.vue"; //版本详情
import EditDrawer from "@/views/application/components/EditDrawer.vue";
import SelectUser from "@/views/system/user/select-user.vue";
import { useListManage } from "@/hooks";
import IrsSelect from "./NodeFormSelect/IrsSelect.vue";
const emit = defineEmits();
const props = defineProps();
// emits: ["callEdit"];
const route = useRoute();
const store = useStore();
const versionList = ref([]);
const showDetail = ref(false);
const showZzdSelcet = ref(false);
const query = reactive();
const url = location.href;
const queryChange = (val) => {
  formInline.value.createdUserCode = val.id;
  formInline.value.createdUserName = val.userName;
  showZzdSelcet.value = false;
  console.log(showZzdSelcet.value);
};
// 浙政钉用户选择
const selectZzdUser = () => {
  showZzdSelcet.value = true;
};

// 应用列表
const appListInfo = ref({list:[]});
const appSearchKey = ref();
const appRemote = (value) => {
  appSearchKey.value = value;
  getAppList();
};

const getAppList = async (current = 1) => {
  let params = {
    search: appSearchKey.value,
    current,
    size: 10,
  };
  console.log(params);
  let { data } = await getAppPageList(params);
  appListInfo.value = data;
};

let formInline = ref({
  currentVersionId: null,
  svcName: "",
  svcUrl: "",
  httpMethod: "",
  appId: "",
  callTimeout: "",
  memo: "",
});
const validateName = (rule, value, callback) => {
  // console.log(formInline.value.uploadIrs);
  let irsModel = formInline.value.uploadIrs;
  let val = value == 0 || value;
  if (irsModel && !val) {
    callback(new Error("IRS模式下为必填项"));
  } else {
    callback();
  }
};

const ruleFormRef = ref(null); // 表单ref
let rules = {
  // 表单校验规则
  svcName: [{ required: true, message: "请输入服务中文名称", trigger: "blur" }],
  httpMethod: [
    { required: true, message: "请选择服务请求", trigger: "change" },
  ],
  svcUrl: [{ required: true, message: "请输入方法名称", trigger: "blur" }],
  appId: [{ required: true, message: "请选择所属应用", trigger: "change" }],
  callTimeout: [
    { required: true, message: "请输入服务调用超时", trigger: "blur" },
  ],
  memo: [{ required: true, message: "请输入服务描述", trigger: "blur" }],
  wrapped: [{ required: true, message: "请选择标准返回", trigger: "change" }],
  shareType: [{ validator: validateName }],
  domainType: [{ validator: validateName }],
  sensitiveLevel: [{ validator: validateName }],
  createdUserCode: [{ validator: validateName }],
};

let uploadIrs = [
  { required: true, message: "请是否上传IRS", trigger: "change" },
];

// let isIrs = () => {
//   return store.getters.name === "超级管理员";
// };
// isIrs() ? rules : (rules = { ...rules, uploadIrs });

// 服务保存
const saveServiceSubmit = (type) => {
  console.log(formInline.value);
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      if (type == "save") {
        let res = await saveService(formInline.value);
        if (res.status == 200) {
          // 添加保存ID
          store.commit("app/PUT_SERVICE_ID", res.data);
          ElMessage({
            type: "success",
            message: "保存成功",
          });
        }
      } else if (type == "creat") {
        let data = store.state.app.serviceBody;
        data.ifParam.adptIfCfgHttp = data.ifParam.adptIfCfgHttp || {};
        data.ifParam.adptIfCfgDb = data.ifParam.adptIfCfgDb || {
          sqlStmt: "",
        };
        data.ifParam.adptIfCfgHttp.inParamsJson = string2obj(
          data.ifParam.adptIfCfgHttp.inParamsJson
        );
        data.ifParam.adptIfCfgDb.inParamsJson = string2Arr(
          data.ifParam.adptIfCfgDb.inParamsJson
        );
        // console.log(res);
        delete data.versionId;
        delete data.ifParam.adptIfCfgHttp?.id;
        delete data.ifParam.adptIfCfgJar?.id;
        delete data.ifParam.adptIfCfgDb?.id;
        data.inParamsList.map((item) => {
          delete item.id;
        });
        data.outParamsList.map((item) => {
          delete item.id;
        });
        store.commit("app/PUT_SERVICE_ALL", data);
        // store.commit("app/PUT_SERVICE_1", formInline.value);
        // store.commit("app/PUT_SERVICE_CREAT", "");
        // console.log("state：", store.state.app.serviceBody);
        emit("callEdit", 2);
      }
    } else {
      console.log("error submit!!");
      return false;
    }
  });
};
// 编辑
const editRow = async (versionId) => {
  let { data } = await versionService(versionId);

  data.ifParam.adptIfCfgHttp = data.ifParam.adptIfCfgHttp || {};
  data.ifParam.adptIfCfgDb = data.ifParam.adptIfCfgDb || { sqlStmt: "" };
  data.ifParam.adptIfCfgHttp.inParamsJson = string2obj(
    data.ifParam.adptIfCfgHttp.inParamsJson
  );
  data.ifParam.adptIfCfgDb.inParamsJson = string2Arr(
    data.ifParam.adptIfCfgDb.inParamsJson
  );

  // console.log(res);
  store.commit("app/PUT_SERVICE_ALL", data);
  store.commit("app/PUT_SERVICE_VERSION", versionId);
  // console.log("state：", store.state.app.serviceBody);
  emit("callEdit", 2);
};
// 作废版本
const cancelVerstion = async (versionId, index) => {
  ElMessageBox.confirm(`请确认版本作废吗？`, {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info",
  }).then(async () => {
    let res = await abolishVersion(versionId);
    // console.log(res);
    // console.log("index", index);
    if (res.status == 200) {
      versionList.value[index].auditSts = "D";
      ElMessage({
        type: "success",
        message: "操作成功",
      });
    } else {
      ElMessage({
        type: "error",
        message: "操作失败",
      });
    }
  });
};
// 查看详情
const detailInfo = ref({});
const getDetailShow = async (id, versionId) => {
  showDetail.value = true;
  detailInfo.value = { id, versionId };
};
let editMode = ref(route.name == "EditService");

// 服务标签列表
const tagsList = ref([]);
const getTagsList = () => {
  let res = getTagsPageList();
  tagsList.value = res;
};

const shareList = ["受限共享", "无条件共享", "非共享"];

const domainList = [
  { id: 1, name: "党政机关整体智治" },
  { id: 2, name: "数字政府" },
  { id: 3, name: "数字经济" },
  { id: 4, name: "数字社会" },
  { id: 5, name: "数字法治" },
  { id: 10, name: "其他" },
];

const sensitiveList = [
  "1级(不敏感) ",
  "2级(低敏感) ",
  "3级(较敏感) ",
  "4级(敏感) ",
  "5级(极敏感) ",
];
watch(
  () => store.state.app.serviceBody,
  (val, old) => {
    formInline.value = val.svc;
    versionList.value = val.svc.versionList;
    // 回调浙政钉姓名
    getUserDetail(val.svc.createdUserCode);
    // 回显所属应用名称
    getAppDetailInfo(val.svc.appId);
  },
  { deep: true }
);

// 应用详情
const getAppDetailInfo = async (id) => {
  console.log(appListInfo.value.list);

  var newArr = appListInfo.value.list.find(function (item) {
    return item.id === id;
  });
  if (!newArr) {
    let { data } = id ? await getAppDetail(id) : {};
    appListInfo.value.list.push(data);
  }

  // console.log(data);
};

// 运维人员姓名回调
const getUserDetail = async (id) => {
  if (id) {
    let { data } = await getUserInfo(id);
    formInline.value.createdUserName = data.userName;
  }
};

onMounted(() => {
  let val = store.state.app.serviceBody;
  formInline.value = val.svc;
  versionList.value = val.svc.versionList;
  getTagsList();
  getAppList();
});
</script>

<style lang="scss" scoped>
.form-base {
  margin-top: 20px;
}

.verstion {
  margin: 20px auto;
  width: 1000px;
}

.verstion-table {
  margin-top: 10px;
}
</style>
